//
//  CircleView.m
//  Footer
//
//  Created by leotao on 16/12/20.
//  Copyright © 2016年 leotao. All rights reserved.
//

#import "CircleView.h"
#import "MJRefresh.h"

@interface CircleView ()

@property (strong, nonatomic) CAShapeLayer *circleLayer;
@property (assign, nonatomic) BOOL endAnimate;

@end

@implementation CircleView

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.circleLayer = [CAShapeLayer layer];
        self.circleLayer.fillColor = [UIColor clearColor].CGColor;
        self.circleLayer.strokeColor = [UIColor colorWithRed:1.0 green:51 / 255.0 blue:34 / 255.0 alpha:1.0].CGColor;
        self.circleLayer.lineWidth = 3;
        [self.layer addSublayer:self.circleLayer];
        
//        CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkAction)];
//        [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
        
        
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    NSLog(@"%s", __func__);
    
    CGFloat width = MIN(self.bounds.size.width, self.bounds.size.height) - 20;
    if (width <= 0 || self.circleLayer.path) return;
    CGFloat height = width;
    CGFloat x = (self.bounds.size.width - width) * 0.5;
    CGFloat y = (self.bounds.size.height - height) * 0.5;
    self.circleLayer.frame = CGRectMake(x, y, width, height);
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:self.circleLayer.bounds];
    self.circleLayer.path = path.CGPath;
}

- (void)setProgress:(CGFloat)progress
{
    if (progress < 0) progress = 0;
    if (progress > 0.8) progress = 0.8;
    
    self.circleLayer.strokeEnd = progress;
    self.circleLayer.affineTransform = CGAffineTransformRotate(CGAffineTransformIdentity, progress * M_PI);
}

- (void)displayLinkAction
{
    NSLog(@"self.circleLayer.frame = %@", NSStringFromCGRect(self.frame));
}

- (void)startAnimating
{
    [self.circleLayer removeAllAnimations];
    
    self.alpha = 1.0;
    self.circleLayer.strokeEnd = 0.8;
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    anim.fromValue = @(M_PI * 0.8);
    anim.toValue = @(M_PI * 2 + M_PI * 0.8);
    anim.repeatCount = INFINITY;
    anim.duration = 0.5;
    [self.circleLayer addAnimation:anim forKey:nil];
}

- (void)endAnimating
{
    [self.circleLayer removeAllAnimations];
    
    
    [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{
        self.progress = 0.0;
        self.alpha = 0;
    } completion:^(BOOL finished) {
        self.alpha = 1.0;
    }];
}


@end
